package com.samphanie.auiu.auth.security.service;

import com.samphanie.auiu.auth.domain.SecurityUser;
import com.samphanie.auiu.auth.service.IUserService;
import com.samphanie.auiu.mbg.model.User;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsPasswordService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * 默认的 UserDetailsPasswordService 实现
 *
 * @author Dries
 * @email 1451691457@qq.com
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class UserDetailsPasswordServiceImpl implements UserDetailsPasswordService {

    private final PasswordEncoder passwordEncoder;
    private final IUserService userService;

    @Override
    public UserDetails updatePassword(UserDetails userDetails, String newPassword) {
        log.error("用户密码更改：{}", newPassword);
        User user = userService.findOptionalByUsername(userDetails.getUsername())
                .map(userFromDb -> userService.saveUser(userFromDb.withPassword(passwordEncoder.encode(newPassword))))
                .orElseThrow();
        return SecurityUser.fromSecurityUser.apply(user);
    }

}
